package cn.asura.otherChat.thread;

import cn.asura.otherChat.server.MyServer;
import cn.asura.otherChat.util.ServerTool;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;

public class ServerThread implements Runnable {

    // 套接字对应的客户端名字
    private final String name;
    // 套接字的编号
    private final int id;

    public ServerThread(int socketNum, String name) {
        this.name = name;
        this.id = socketNum;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader;

        try {
            bufferedReader = new BufferedReader(new InputStreamReader(MyServer.sockets[id].getInputStream()));

            while (true) {
                // 从输入流获取客户端的信息
                String msg = bufferedReader.readLine();
                if (null == msg || "".equals(msg)) {
                    continue;
                }
                if ("bye".equalsIgnoreCase(msg)) {
                    System.out.println("服务器：" + name + "下线了");
                    ServerTool.shareMsg(id, "服务器", name + "下线了");
                    break;
                } else if ("send".equalsIgnoreCase(msg)) {
                    // 先读取文件名
                    String fileName = bufferedReader.readLine();
                    // 读取客户端发送来的文件并保存到服务器目录
                    ServerTool.receiveFile(id, fileName, name);
                    // 把文件名群发给所有的其他客户端
                    ServerTool.shareMsg(id, name, "分享了文件 " + fileName);
                } else if ("download".equalsIgnoreCase(msg)) {
                    // 先读取文件名
                    String fileName = bufferedReader.readLine();
                    // 读取服务端的文件并发送给到用户
                    File file = new File("./storage/server/" + fileName);
                    ServerTool.sendFileToClient(id, file, name);
                } else {
                    // 共享信息
                    ServerTool.shareMsg(id, name, msg);
                }
            }
        } catch (SocketException e) {
            System.out.println(name + "被异常中断， 信息：" + e.getMessage());
            if (MyServer.sockets[id].isClosed()) {
                System.out.println("socket被异常关闭");
            } else {
                System.out.println("socket还未被关闭");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
